package cn.ekuma.epos.crm.physicalbond;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.openbravo.data.loader.query.QBF;
import com.openbravo.pos.base.AppLocal;
import e.odbo.data.bean.IKeyed;
import cn.ekuma.data.ui.swing.AbstractDAOJEditor;
import cn.ekuma.epos.crm.dialog.JCardNumBatchCreateDialog;
import cn.ekuma.epos.crm.physicalbond.model.PhysicalBondTableModel;

import cn.ekuma.epos.db.table.crm.physicalbond.I_PhysicalBond;
import cn.ekuma.epos.module.CRM_UI_Swing_Model;
import cn.ekuma.epos.panel.AbstractSingleJModelFinishingPanel;
import cn.ekuma.util.RandomWordGenerator;

import com.openbravo.bean.crm.physicalbond.PhysicalBond;
import com.openbravo.bean.crm.voucher.VoucherOPEnum;
import com.openbravo.bean.infobean.CustomerInfo;
import com.openbravo.bean.infobean.UserInfo;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.query.QBFCompareEnum;
import com.openbravo.data.loader.query.QBFParameter;
import com.openbravo.data.loader.query.QBFParameters;
import com.openbravo.data.loader.ui.JQBFParametersPanel;
import com.openbravo.data.user.DirtyManager;
import com.openbravo.format.Formats;

import com.openbravo.pos.base.AppView;
import com.openbravo.pos.base.BeanFactoryException;
import com.openbravo.pos.panels.JCustomerFinder;
import com.openbravo.pos.panels.event.TimeCycleChangedEvent;

public class JPhysicalBondFinishing extends AbstractSingleJModelFinishingPanel<PhysicalBond> {

	private JButton btnLost;
	private JButton btnRecovery;
	private JButton btnBack;
	private JButton btnInvalid;
	private JButton btnChangepassword;
	private JButton btnCustomer;
	private UserInfo useInfo;
	private RandomWordGenerator randomWordGenerator=RandomWordGenerator.instance(8);

	public JPhysicalBondFinishing() {
		super(new PhysicalBondTableModel());
	}

	@Override
	public String getTitle() {
		//return AppLocal.getIntString("label.Voucher");
		return null;
	}

	@Override
	public void initFinishPanel(AppView app) throws BeanFactoryException {
          useInfo=app.getUserInfo();
          paintOpButtonState(null);
	}

	@Override
	public Object createValue() throws BasicException {
		Object[] afilter = new Object[6];

		// Date range
		Object startdate = Formats.TIMESTAMP
				.parseValue(jTxtStartDate.getText());
		Object enddate = Formats.TIMESTAMP.parseValue(jTxtEndDate.getText());

		afilter[0] = (startdate == null) ? QBFCompareEnum.COMP_NONE
				: QBFCompareEnum.COMP_GREATEROREQUALS;
		afilter[1] = startdate;
		afilter[2] = (enddate == null) ? QBFCompareEnum.COMP_NONE
				: QBFCompareEnum.COMP_LESS;
		afilter[3] = enddate;

		//category
		afilter[4] = QBFCompareEnum.COMP_NONE;
		afilter[5] = null;
		
		return afilter;
	}

	String[] fields=new String[]{I_PhysicalBond.CREATEDATE, I_PhysicalBond.CREATEDATE, I_PhysicalBond.CUSTOMER_ID};
	public void reQuery() {
		QBF qbf=QBF.c();
		for(int i=0;i<beforeFilterParas.length;i=i+2)
			if(beforeFilterParas[i]!=QBFCompareEnum.COMP_NONE)
				qbf.and(new QBFParameter(fields[i/2],(QBFCompareEnum) beforeFilterParas[i],beforeFilterParas[i+1]));
		try {
			tableModel.resert(dlSales.query(PhysicalBond.class, qbf.build()));
			if (beforeFilterParas[1] != null)
				jTxtStartDate.setText(Formats.TIMESTAMP
						.formatValue(beforeFilterParas[1]));
			else
				jTxtStartDate.setText(null);
			if (beforeFilterParas[3] != null)
				jTxtEndDate.setText(Formats.TIMESTAMP
						.formatValue(beforeFilterParas[3]));
			else
				jTxtEndDate.setText(null);
		} catch (BasicException ex) {
			new MessageInf(ex).show(this);
		}
	}
	
	@Override
	public void timeCycleChanged(TimeCycleChangedEvent e) {
		if (beforeFilterParas == null)
			try {
				beforeFilterParas = (Object[]) createValue();
			} catch (BasicException ex) {
				new MessageInf(ex).show(this);
				return;
			}
			
			// Date range
			Object startdate = e.getStartDate();
			Object enddate =e.getEndDate();

			beforeFilterParas[0] = (startdate == null) ? QBFCompareEnum.COMP_NONE
					: QBFCompareEnum.COMP_GREATEROREQUALS;
			beforeFilterParas[1] = startdate;
			beforeFilterParas[2] = (enddate == null) ? QBFCompareEnum.COMP_NONE
					: QBFCompareEnum.COMP_LESS;
			beforeFilterParas[3] = enddate;
			reQuery();
		
	}

	@Override
	protected void m_jBarcode1ActionPerformed(ActionEvent e) {
		String sCode = inputCode.getText();
		if (sCode.isEmpty()) {
			return;
		}
		QBFParameters paras=new QBFParameters();
		paras.or(new QBFParameter(I_PhysicalBond.VOUCHERNUM).equal(sCode));  
		try {
			tableModel.resert(dlSales.query(PhysicalBond.class, paras));
		} catch (BasicException e1) {
			new MessageInf(e1).show(this);
		} 
	}

	@Override
	protected void configNavigator(JPanel jNavigatorToolBar, JPanel jNavigator) {
		JPanel panel_3 = new JPanel();
		jNavigator.add(panel_3, "QBFPanel");
		panel_3.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_2 = new JPanel();
		panel_2.setPreferredSize(new Dimension(10, 155));
		panel_3.add(panel_2, BorderLayout.NORTH);
		
		btnLost = new JButton(AppLocal.getIntString("label.StoreValueCardOPEnum.lost"));
		btnLost.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PhysicalBond card=getSelectedObj();
				if(card==null)
					return;
				try {
					//customerStoreValueCardOp(card,VoucherOPEnum.lost);
					dlSales.updateByField(PhysicalBond.class,
							card, I_PhysicalBond.STATE,
							PhysicalBond.STATE_Loss);
					card.setState(PhysicalBond.STATE_Loss);
					paintOpButtonState(card);
				} catch (BasicException e1) {
					new MessageInf(e1).show(JPhysicalBondFinishing.this);
				}
			}
		});
		panel_2.setLayout(new GridLayout(0, 2, 0, 0));
		panel_2.add(btnLost);
		
		btnRecovery = new JButton(AppLocal.getIntString("label.StoreValueCardOPEnum.recovery"));
		btnRecovery.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PhysicalBond card=getSelectedObj();
				if(card==null)
					return;
				try {
					//customerStoreValueCardOp(card,VoucherOPEnum.recovery);
					dlSales.updateByField(PhysicalBond.class,
							card, I_PhysicalBond.STATE,
							PhysicalBond.STATE_UseAble);
					card.setState(PhysicalBond.STATE_UseAble);
					paintOpButtonState(card);
				} catch (BasicException e1) {
					new MessageInf(e1).show(JPhysicalBondFinishing.this);
				}
			}
		});
		panel_2.add(btnRecovery);
		
		btnBack = new JButton(AppLocal.getIntString("label.StoreValueCardOPEnum.back"));
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PhysicalBond card=getSelectedObj();
				if(card==null)
					return;
				try {
					//customerStoreValueCardOp(card,VoucherOPEnum.back);
					dlSales.updateByField(PhysicalBond.class,
							card, I_PhysicalBond.STATE,
							PhysicalBond.STATE_Back);
					card.setState(PhysicalBond.STATE_Back);
					paintOpButtonState(card);
				} catch (BasicException e1) {
					new MessageInf(e1).show(JPhysicalBondFinishing.this);
				}
			}
		});
		panel_2.add(btnBack);
		
		btnInvalid = new JButton(AppLocal.getIntString("label.StoreValueCardOPEnum.invalid"));
		btnInvalid.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				PhysicalBond card=getSelectedObj();
				if(card==null)
					return;
				try {
					//customerStoreValueCardOp(card,VoucherOPEnum.invalid);
					dlSales.updateByField(PhysicalBond.class,
							card, I_PhysicalBond.STATE,
							PhysicalBond.STATE_Invalid);
					card.setState(PhysicalBond.STATE_Invalid);
					paintOpButtonState(card);
				} catch (BasicException e1) {
					new MessageInf(e1).show(JPhysicalBondFinishing.this);
				}
			}
		});
		panel_2.add(btnInvalid);
			
		
		btnChangepassword = new JButton(AppLocal.getIntString("title.changepassword"));
		panel_2.add(btnChangepassword);
		
		 btnCustomer = new JButton(AppLocal.getIntString("label.customer"));
		 btnCustomer.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					PhysicalBond card=getSelectedObj();
					if(card==null)
						return;
					JCustomerFinder finder = JCustomerFinder.getCustomerFinder(JPhysicalBondFinishing.this, mode.getDLERP(),true);
			        finder.search(null);
			        finder.setVisible(true);
			        CustomerInfo customer= finder.getSelectedCustomer();
			        try {
					if (customer == null) {
						dlSales.updateByField(PhysicalBond.class,
								card, I_PhysicalBond.CUSTOMER_ID,
								null);
						card.setCustomerId(null);

					} else {
						dlSales.updateByField(PhysicalBond.class,
								card, I_PhysicalBond.CUSTOMER_ID,
								customer.getId());
						card.setCustomerId(customer.getId());
					}
					paintOpButtonState(card);
			        } catch (BasicException e1) {
			        	new MessageInf(e1).show(JPhysicalBondFinishing.this);
					}
			        
				}
		 });
		 
		panel_2.add(btnCustomer);
		
		JButton btnNewButton_6 = new JButton(AppLocal.getIntString("label.batchCreateCard"));
		btnNewButton_6.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JCardNumBatchCreateDialog createDialog=JCardNumBatchCreateDialog.newJDialog(JPhysicalBondFinishing.this);
				createDialog.setVisible(true);
				ArrayList<PhysicalBond> cards=new ArrayList<PhysicalBond>();
				PhysicalBond card;
				Date now=new Date();
				for(String cardNum:createDialog.getStringList()){
					card=new PhysicalBond();
					card.setVoucherNum(cardNum);
					card.setCreateDate(now);
					card.setState(PhysicalBond.STATE_Unknown);
					card.setValidityDate(now);
					card.setValidityCode(randomWordGenerator.random());
					cards.add(card);
				}
				try {
					dlSales.insertObjs(cards);
					tableModel.resert(cards);
				} catch (BasicException e1) {
					new MessageInf(e1).show(JPhysicalBondFinishing.this);
				}
			}
		});
		
		panel_2.add(btnNewButton_6);
		
		JLabel label = new JLabel("");
		panel_2.add(label);
		
		JQBFParametersPanel qbfPanel=new JQBFParametersPanel(){
			@Override
			public void doQBFParametersFilter(QBFParameters paras) {
				try {
					tableModel.resert(dlSales.query(PhysicalBond.class, paras));
				} catch (BasicException e) {
					new MessageInf(e).show(this);
				}
			}
        };
        qbfPanel.setShowFieldCount(6);
        qbfPanel.setFields(PhysicalBondTableModel.getQBFFields());
        panel_3.add(qbfPanel, BorderLayout.CENTER);
		
	}

	//private void customerStoreValueCardOp(Voucher card,VoucherOPEnum opType) throws BasicException{
	//	dlSales.voucherDiaryInsert(opType,createDiary(card,opType));
	//}
	

	@Override
	protected void fireBaseBeanChanged(IKeyed key, PhysicalBond object) {
		super.fireBaseBeanChanged(key, object);
		paintOpButtonState(object);
	}

	
	private void paintOpButtonState(PhysicalBond obj){
		btnLost.setEnabled(false);
		btnRecovery.setEnabled(false);
		btnBack.setEnabled(false);
		btnInvalid.setEnabled(false);
		btnChangepassword.setEnabled(false);
		btnCustomer.setEnabled(false);
		if(obj!=null)
		   switch(obj.getState()){ 
		     case PhysicalBond.STATE_Invalid:
		    	 btnRecovery.setEnabled(true);
		    	 break;
		     case PhysicalBond.STATE_Loss:
		    	 btnRecovery.setEnabled(true);
		    	 btnInvalid.setEnabled(true);
		    	 break;
		     case PhysicalBond.STATE_Unknown:
		    	 btnRecovery.setEnabled(true);
		    	 break;
		     case PhysicalBond.STATE_UseAble:
		        btnLost.setEnabled(true);
		 		btnBack.setEnabled(true);
		 		btnInvalid.setEnabled(true);
		 		btnChangepassword.setEnabled(true);
		 		if(obj.getCustomerId()==null)
		 		   btnCustomer.setEnabled(true);
		   }
	}

	@Override
	protected AbstractDAOJEditor<PhysicalBond> getEditor() {
		return new PhysicalBondEditor(new DirtyManager(),mode.getDLERP());
	}

	@Override
	public String getModelName() {
		return CRM_UI_Swing_Model.MODEL_NAME;
	}

}
